<?php


namespace App\Admin\Actions\Order;


trait AssessedCoupon
{
    /**
     * 券后价分摊
     * @return array|string[]
     */
    protected function calculateDistributedPrices()
    {
        //统计优惠金额
        $couponValue = $this->order->goods_amount - $this->order->pay_amount - $this->order->user_money - $this->order->shipping_fee - $this->order->user_credit;

        $items = $this->order->orderGoods; //商品合集

        // 计算所有商品的总值
        $totalItemValueInCents = 0;
        foreach ($items as $item) {
            if ($item->with_coupon) {
                $totalItemValueInCents += round($item['price'] * $item['number'] * 100); // 商品总值（分）
            }
        }

        // 将金额转换为分（整数）
        $totalPriceInCents = $totalItemValueInCents; // 总价（分）
        $couponValueInCents = round($couponValue * 100); // 优惠券金额（分）

        if ($couponValueInCents == 0) {
            foreach ($items as $item) {
                $item->real_price = $item->price;
                $item->save();
            }
            return;
        }

        // 确保优惠券金额不超过总价
        if ($couponValueInCents > $totalPriceInCents) {
            $couponValueInCents = $totalPriceInCents; // 限制优惠券金额
        }

        // 计算券后价
        $finalPriceInCents = $totalPriceInCents - $couponValueInCents;


        // 捕获每个商品的券后单价
        $itemUnitPrices = [];
        $allocatedCents = 0; // 分配的总金额

        // 计算每个商品的券后单价
        foreach ($items as $item) {
            if ($item->with_coupon) {
                // 计算当前商品的总值
                $itemTotalInCents = round($item['price'] * $item['number'] * 100);

                if ($totalItemValueInCents > 0) {
                    // 计算每个商品的券后单价
                    $itemUnitPriceInCents = floor(($itemTotalInCents / $totalItemValueInCents) * $finalPriceInCents);

                    $item->real_price = bcdiv(bcdiv($itemUnitPriceInCents, $item['number'], 3), 100, 3); //计算每个单品的券后单价

                    $itemUnitPrices[] = $itemUnitPriceInCents; // 保存单价（分）
                    $allocatedCents += $itemUnitPriceInCents; // 累加已分配金额
                } else {
                    $itemUnitPrices[] = 0; // 如果没有商品则返回0
                }
            } else {
                $item->real_price = $item->price;
            }
            $item->save();
        }
        // 处理可能的误差，通过分配差额调整最后一个商品
        $difference = $finalPriceInCents - $allocatedCents;
        if ($difference != 0) {
            $itemUnitPrices[count($itemUnitPrices) - 1] += $difference; // 调整最后一个商品进行补偿
        }
//        foreach ($this->order->orderGoods->where('with_coupon', 1) as $keys => $item) {
//            $item->real_price = bcdiv(bcdiv($itemUnitPrices[$keys], 100, 2), $item->number, 3);
//            $item->save();
//
//        }
    }

}